// 景点详情页
const app = getApp()
// 导入模拟数据服务
import mockApi from '../../services/mock.js'

// 页面配置对象
const pageConfig = {
  data: {
    attractionId: null,
    attraction: null,
    isLoading: true,
    hasError: false,
    errorMsg: '',
    userInfo: null,
    isLiked: false,
    comment: '',
    canComment: false
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        attractionId: options.id
      })
      this.fetchAttractionDetail(options.id)
      this.checkUserInfo()
    } else {
      this.setData({
        hasError: true,
        errorMsg: '景点ID不存在',
        isLoading: false
      })
    }
  },

  onShow: function() {
    // 如果用户信息已更新，刷新页面数据
    if (app.globalData.userInfo && !this.data.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
    }
  },

  // 获取景点详情
  fetchAttractionDetail: function(id) {
    this.setData({ isLoading: true, hasError: false })
    
    // 使用模拟API服务
    mockApi.getAttractionById(id)
      .then(data => {
        this.setData({
          attraction: data,
          isLoading: false
        })
        
        // 检查用户是否已点赞
        if (this.data.userInfo) {
          this.checkIfLiked()
        }
      })
      .catch(err => {
        console.error('获取景点详情失败', err)
        this.setData({
          hasError: true,
          errorMsg: err.message || '网络异常，请稍后重试',
          isLoading: false
        })
      })
  },

  // 检查用户信息
  checkUserInfo: function() {
    const userInfo = app.globalData.userInfo
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        canComment: true
      })
      
      // 如果已加载景点信息，检查是否已点赞
      if (this.data.attraction) {
        this.checkIfLiked()
      }
    }
  },

  // 检查是否已点赞
  checkIfLiked: function() {
    if (!this.data.userInfo || !this.data.attractionId) return
    
    // 使用模拟API服务
    mockApi.checkLikeStatus(this.data.userInfo.id, this.data.attractionId)
      .then(res => {
        this.setData({
          isLiked: res.isLiked
        })
      })
      .catch(err => {
        console.error('检查点赞状态失败', err)
      })
  },

  // 点赞/取消点赞
  toggleLike: function() {
    if (!this.data.userInfo) {
      this.goToLogin()
      return
    }
    
    const action = !this.data.isLiked
    
    // 先进行乐观UI更新
    const attraction = this.data.attraction
    attraction.likeCount = this.data.isLiked 
      ? attraction.likeCount - 1 
      : attraction.likeCount + 1
    
    this.setData({
      isLiked: !this.data.isLiked,
      attraction: attraction
    })
    
    // 使用模拟API服务
    mockApi.toggleLike(this.data.userInfo.id, this.data.attractionId, action)
      .then(res => {
        if (res.success) {
          wx.showToast({
            title: this.data.isLiked ? '已点赞' : '已取消点赞',
            icon: 'success',
            duration: 1500
          })
        } else {
          // 如果请求失败，回滚UI状态
          attraction.likeCount = this.data.isLiked 
            ? attraction.likeCount + 1 
            : attraction.likeCount - 1
          
          this.setData({
            isLiked: !this.data.isLiked,
            attraction: attraction
          })
          
          wx.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          })
        }
      })
      .catch(() => {
        // 如果请求失败，回滚UI状态
        attraction.likeCount = this.data.isLiked 
          ? attraction.likeCount + 1 
          : attraction.likeCount - 1
        
        this.setData({
          isLiked: !this.data.isLiked,
          attraction: attraction
        })
        
        wx.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        })
      })
  },

  // 评论内容变化
  onCommentInput: function(e) {
    this.setData({
      comment: e.detail.value
    })
  },

  // 提交评论
  submitComment: function() {
    if (!this.data.userInfo) {
      this.goToLogin()
      return
    }
    
    if (!this.data.comment.trim()) {
      wx.showToast({
        title: '评论内容不能为空',
        icon: 'none'
      })
      return
    }
    
    const commentData = {
      userId: this.data.userInfo.id,
      attractionId: this.data.attractionId,
      content: this.data.comment,
      createTime: new Date().getTime()
    }
    
    // 使用模拟API服务
    mockApi.addComment(commentData)
      .then(res => {
        if (res.success) {
          // 更新评论列表
          const newComment = {
            id: res.id || Date.now().toString(),
            user: {
              id: this.data.userInfo.id,
              nickName: this.data.userInfo.nickName,
              avatarUrl: this.data.userInfo.avatarUrl
            },
            content: this.data.comment,
            createTime: new Date().getTime()
          }
          
          const attraction = this.data.attraction
          if (!attraction.comments) {
            attraction.comments = []
          }
          attraction.comments.unshift(newComment)
          
          this.setData({
            attraction: attraction,
            comment: ''
          })
          
          wx.showToast({
            title: '评论成功',
            icon: 'success'
          })
        } else {
          wx.showToast({
            title: '评论失败，请重试',
            icon: 'none'
          })
        }
      })
      .catch(() => {
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
      })
  },

  // 跳转到登录页
  goToLogin: function() {
    wx.showModal({
      title: '提示',
      content: '您需要登录后才能操作',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/index'
          })
        }
      }
    })
  },

  // 显示地图
  openLocation: function() {
    if (!this.data.attraction || !this.data.attraction.latitude || !this.data.attraction.longitude) {
      wx.showToast({
        title: '暂无位置信息',
        icon: 'none'
      })
      return
    }
    
    wx.openLocation({
      latitude: parseFloat(this.data.attraction.latitude),
      longitude: parseFloat(this.data.attraction.longitude),
      name: this.data.attraction.name,
      address: this.data.attraction.address,
      scale: 18
    })
  },

  // 预览图片
  previewImage: function(e) {
    const current = e.currentTarget.dataset.src
    const urls = this.data.attraction.images.map(img => img.url)
    
    wx.previewImage({
      current: current,
      urls: urls
    })
  },

  // 分享
  onShareAppMessage: function() {
    return {
      title: this.data.attraction ? this.data.attraction.name : '沙扒湾景点推荐',
      path: `/pages/attractions/detail?id=${this.data.attractionId}`,
      imageUrl: this.data.attraction && this.data.attraction.coverImage ? this.data.attraction.coverImage : ''
    }
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    if (this.data.attractionId) {
      this.fetchAttractionDetail(this.data.attractionId)
      
      setTimeout(() => {
        wx.stopPullDownRefresh()
      }, 1000)
    } else {
      wx.stopPullDownRefresh()
    }
  },

  // 重试加载
  retryLoading: function() {
    this.fetchAttractionDetail(this.data.attractionId)
  }
}

// 适配微信原生环境
Page(pageConfig)

// 适配uni-app导出
export default pageConfig 